layui.use(['jquery','http','form','layuimini'],function(){
    let $ = layui.jquery,
        form = layui.form,
        http = layui.http,
        tipsBox;
    form.on('submit(common-submit-save)',function(res){
        const data = res.field,
        url = $(res.elem).attr('data-save-url'),cb = $(res.elem).attr('data-callback'),
            table_id = $(res.elem).attr('data-table-id');
        if( !url || url == undefined ){
            layer.msg('必须设置按钮的data-save-url属性为提交目标的地址')
            return ;
        }
        http.post(url,{data:data}).done(function(res){
            if(res.code === 200){
                setTimeout(() => {
                    layer.close(openBox)
                    if( table_id ){
                        window[table_id].reload()
                    } else {
                        tb.reload()
                    }
                }, 1200);
                layer.msg(res.msg)
                typeof window[cb] === 'function' ?  window[cb]() : null;
            }

        })
    })

    $('body').on('click','.common-search',function(){
        let key = $(this).parents('.layui-form').find('input[name="key"]').val();
        key = key.replace(/^\s+|\s+$/g,"");
        window.search_key = key;
        const callback = $(this).attr('data-search-fun');
        if( key ){
            $(this).parents('.layui-form').find('input[name="key"]').val(key)
            $(this).parent('div').nextAll("#common-search-tips").text('搜索词【'+key+'】');
            $(this).attr('data-search','yes');
            typeof window[callback] === 'function' ? window[callback](key) :
                tb.reload({
                    where:{key:key},
                    page:{curr:1}
                })
        }
  })
    $('body').on('click','#common-clear-input',function(){
        const dom = $('input[name="key"]');
        window.search_key = null
        dom.val('');
        const is = $('.common-search').attr('data-search');
        if( is == 'yes') {
                dom.trigger('propertychange')
            }
    })
    $('body').on('keydown','input[name="key"]',function(e){
        if (event.keyCode == "13") {
            $('.common-search').click();
        }
    })
    $('body').on('input propertychange','input[name="key"]' ,function(e){
        e.stopPropagation();
        const key = $('input[name="key"]').val();
        const is = $('.common-search').attr('data-search');
        if( !key && is === 'yes')
        {
            $("#common-search-tips").text('')
            $('.common-search').attr('data-search','no');
            tb.reload({
                where:null,
                limit:15,
                limits:[15,30,45,60,120],
                page: {
                    curr: 1
                    }
            });
        }
    })
    $('body').off('click','.common-reload').on('click','.common-reload',function () {
        let cb = $(this).attr('data-callback') ,tab_id = $(this).attr('data-table-id'),
            reload_tab_id =  ( tab_id && typeof window[tab_id] === 'object' ) ? window[tab_id] :  tb;
        layer.load(0,{time: 100})
            reload_tab_id.reload({
                where:null,
                page:{
                    curr:1
                }
            })
        typeof window[cb] === 'function' &&  window[cb]();
    })
    $('body').on('mouseenter','[data-tip]',function(){
        const text = $(this).attr('data-tip');
        tipsBox = layer.tips(text, $(this), {text: [2, '#2f4056'],tips:3,time:0});
    })
    $('body').on('mouseleave','[data-tip]',function(){
        layer.close(tipsBox)
    })
    $(document).on('click','#del-durl-button',function(){
        $(this).parents('.layui-form-item').remove()
    })
    $('body').on('click','.delete-all',function(){
        const tid = $(this).attr('data-table-id'), _this = this
        const url = $(this).attr('data-del-url')
        if(!tid || !url) {
            layer.alert('该元素没有设置data-table-id属性或data-del-url属性');
            return
        }
        const ids = layuimini.ids(table.checkStatus(tid).data);
        if( ids.length < 1 )
        {
            layer.msg('请选择至少一个！');
            return
        }
        let msg = $(this).attr('data-confirm-msg') || '确定全部删除？';
        layer.confirm(msg,{icon:3, title:'确认操作'},function(index){
            http.post(url,{ids:ids}).done(function(res){
                if(res.code == 200 )
                {
                    setTimeout(() => {
                        let p = $(_this).parents('.layui-form').find('.common-reload')
                        if(p.length > 0){
                            p.click()
                        } else {
                            tb.reload();
                        }

                    }, 600);
                    layer.close(index)
                }
                layer.msg(res.msg)
            })
        })
    });
    $(document).off('blur','input[data-blur]').on('blur','input[data-blur]',function () {
            let fun = $(this).attr('data-blur');
            if( typeof window[fun] === 'function'){
                window[fun]( $(this).val(), $(this) );
            }
    });
    $(document).off('click','[data-click]').on('click','[data-click]',function () {
        let fun = $(this).attr('data-click');
        if( typeof window[fun] === 'function' ) {
            window[fun]($(this));
        }
    })
});
window.common_add_click = function ( o ) {
    const url = o.attr('data-page');
    if( !url ){
        layer.alert('必须设置按钮的data-page属性为要load进来的页面，谢谢！');
        return
    }
    const func = o.attr('data-callback'),
        cancel = o.attr('data-callback-cancel'),
        end = o.attr('data-callback-end');
    let h = o.attr('data-box-h');
    let w = o.attr('data-box-w');
    http.getHtml(url,function(res){
        w = w ? w : '600px';
        h = h ? h : 'auto' ;
        window.openBox = layer.open({
            type:1,
            area:[w,h],
            content:res,
            success:function (e) {
                typeof window[func] ===  'function'  ? window[func](e) : null
            },
            cancel:function(e) {
                typeof window[cancel] === 'function' ? window[cancel](e) : null
            },
            end:function() {
                typeof window[end] === 'function'? window[end]() : null
            }
        })
    })
}
window.format_num = function (number) {
    if (!number || number == null ) return 0
    const sign = number.indexOf("-") > 0 ? '-' : '';
    let cents = number.indexOf(".") > 0 ? number.substr(number.indexOf(".")) : '';
    cents = ( cents.length > 1 && cents > 0)? cents : '' ;
    let num = number.indexOf(".")>0 ? number.substring(0,(number.indexOf("."))) : number ;
    if('' === cents){
        if(num.length>1 && '0' === num.substr(0,1)){
            return 'Not a Number!';
        }
    }
    if(num.length>1 && '0' === num.substr(0,1)){return 'Not a Number!';}
    for (let i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    {
        num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
    }
    //将数据（符号、整数部分、小数部分）整体组合返回
    return (sign + num + cents);

}
